/**
 * Created by root on 2017/8/11.
 * 编辑页面 读取cookie note
 */

window.onload=function(){
    var mytitle=document.getElementById("mytitle");
    var mytext=document.getElementById("mytext");
    var save_button=document.getElementById("save_button");
    var return_button=document.getElementById("return_button");
    function getCookie(cname)
    {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++)
        {
            var c = ca[i].trim();
            if (c.indexOf(name)==0) return c.substring(name.length,c.length);
        }
        return "";
    }
    //加载编辑笔记的内容
    var x=getCookie("note");
    //var note_edit_id=document.getElementById("note_edit_id");
    //note_edit_id.innerHTML=x;
    if(x!=="")
    {
        var request=new XMLHttpRequest();
        request.open("POST","i/note/note/getNote",true);
        request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var message="noteId="+x;
        request.onreadystatechange=function(){
            if(request.readyState==4)
            {
                if(request.status==200)
                {
                    var data=JSON.parse(request.responseText);
                    if(data.result==1)
                    {
                        alert("edit success");
                        mytitle.value=data.title;
                        //mydate.innerHTML=data.updateTime;
                        mytext.value=data.text;
                    }
                }
                else
                {
                    alert("请求错误"+request.status);
                }
            }
        }
        request.send(message);
    }

    save_button.onclick=function(){
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.open("POST","i/note/note/update_note",true);           //更新笔记
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        var message_send="noteId="+x+"&title="+mytitle.value+"&text="+mytext.value;
        xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState==4)
            {
                if(xmlhttp.status==200)
                {
                    var data=JSON.parse(xmlhttp.responseText);
                    if(data.result==1)
                    {
                        alert("保存成功！");
                        window.location.href="Main.html";
                    }
                }
            }
            else{
                alert("保存失败!");
            }
        }
        xmlhttp.send(message_send);
    }

    return_button.onclick=function(){
        window.location.href="Main.html";
    }

}